<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?php echo $current_canvas ? $current_canvas['name'] . ' - HTML原型画板' : 'HTML原型画板管理'; ?></title>
    <link rel="stylesheet" href="assets/css/canvas.css">
    <!-- 引入图标 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="assets/js/jquery.js"></script>
</head>
<body>
<div class="container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
        <div class="toolbar-title" style="display:flex;gap:10px;">
            <h4>HTML原型画板</h1>
            <button class="btn btn-sm " onclick="window.location.href='index.php'" >首页</button>
            <button class="btn btn-sm btn-primary" id="toggeSetting">收起左侧</button>
        </div>
        <div class="toolbar-actions">
            <?php if ($current_canvas): ?>
                <button class="toolbar-btn" id="resetViewBtn">
                    <i class="fa-solid fa-arrows-up-down-left-right"></i>
                    <span>重置视图</span>
                </button>
                <div class="scale-control" style="display: flex; align-items: center; gap: 8px;">
                    <button class="toolbar-btn" id="zoomOutBtn">
                        <i class="fa-solid fa-minus"></i>
                    </button>
                    <span id="scaleDisplay"><?php echo $current_canvas['canvas_view']['scale']; ?>%</span>
                    <button class="toolbar-btn" id="zoomInBtn">
                        <i class="fa-solid fa-plus"></i>
                    </button>
                </div>
            <?php endif; ?>
            <a href="?action=logout" class="toolbar-btn danger">
                <i class="fa-solid fa-sign-out-alt"></i>
                <span>退出</span>
            </a>
        </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
         <!-- 左侧树状画板管理目录 -->
        <div class="tree-sidebar">
            <div class="tree-header">
                <h3>画板管理</h3>
                <button class="btn btn-sm btn-primary" id="addCanvasBtn">
                    <i class="fa-solid fa-plus"></i> 新建画板
                </button>
            </div>
            

            
            <!-- 新建画板表单（默认隐藏） -->
            <div class="tree-form" id="newCanvasForm" style="display: none; padding: 10px;">
                <input type="text" class="form-input" id="newCanvasName" placeholder="输入画板名称">
                <div style="display: flex; gap: 5px; margin-top: 8px;">
                    <button class="btn btn-sm btn-primary" id="confirmCreateCanvas">确认</button>
                    <button class="btn btn-sm btn-secondary" id="cancelCreateCanvas">取消</button>
                </div>
            </div>
            
            <!-- 树状目录列表 -->
            <div class="tree-list">
                <?php if (empty($current_canvas_list)): ?>
                    <div class="empty-tree">暂无画板，点击新建按钮创建</div>
                <?php else: ?>
                    <ul>
                        <?php foreach ($current_canvas_list as $can_id => $item): ?>
                            <li class="tree-item <?php echo isset($current_canvas) && $can_id == $_GET['canvas_id'] ? 'active' : ''; ?>">
                                <div class="tree-item-content">
                                    <a href="?action=edit_canvas&project_id=<?php echo $project_id; ?>&canvas_id=<?php echo $can_id; ?>" class="tree-item-name">
                                        <?php echo htmlspecialchars($item['name']); ?>
                                        <span class="child-count"><?php echo count($item['areas']); ?> 个画板</span>
                                    </a>
                                </div>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php endif; ?>
            </div>
        </div>
<?php if($current_canvas){ ?>        
        <!-- 左侧面板 -->
        <div class="sidebar">
            <!-- 画板名称编辑 -->
            <div class="canvas-name-edit">
                <input type="text" class="canvas-name-input" id="canvasNameInput"
                       value="<?php echo htmlspecialchars($current_canvas['name']); ?>">
                <button class="canvas-name-btn btn-save" id="saveCanvasNameBtn">保存</button>
                <button class="canvas-name-btn btn-delete" id="deleteCanvasBtn"
                        onclick="return confirm('确定删除该画板？所有区域将被删除！')">删除
                </button>
            </div>

            <!-- 添加新区域 -->
            <div class="panel">
                <div class="panel-title">添加新区域</div>
                <form id="addAreaForm">
                    <input type="hidden" name="action" value="add_area">
                    <input type="hidden" name="canvas_id" value="<?php echo $canvas_id; ?>">
                    <input type="hidden" name="project_id" value="<?php echo $project_id; ?>">
                    <div class="form-group">
                        <label class="form-label" for="area_name">区域名称</label>
                        <input type="text" class="form-input" id="area_name" name="area_name" required
                               placeholder="例如：首页Banner、登录表单">
                    </div>

                    <div class="form-group">
                        <label class="form-label" for="resolution">选择分辨率</label>
                        <select class="form-select" id="resolution" name="resolution" required>
                            <option value="">-- 选择预设分辨率 --</option>
                            <optgroup label="PC常用分辨率">
                                <?php foreach ($pc_res as $res): ?>
                                    <option value="<?php echo $res['w'] . 'x' . $res['h']; ?>"><?php echo $res['name']; ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                            <optgroup label="手机常用分辨率">
                                <?php foreach ($mobile_res as $res): ?>
                                    <option value="<?php echo $res['w'] . 'x' . $res['h']; ?>"><?php echo $res['name']; ?></option>
                                <?php endforeach; ?>
                            </optgroup>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label" for="html_content">HTML内容</label>
                        <textarea class="form-textarea" id="html_content" name="html_content" required
                                  placeholder="输入区域的HTML代码"></textarea>
                    </div>

                    <button type="submit" class="btn btn-primary" style="width:100%;">添加到画板</button>
                </form>
            </div>

            <!-- 区域列表 -->
            <div class="panel">
                <div class="panel-title">区域列表（共 <?php echo count($current_canvas['areas']); ?> 个）</div>
                <?php if (empty($current_canvas['areas'])): ?>
                    <div class="alert alert-success">暂无区域，点击上方添加按钮创建</div>
                <?php else: ?>
                    <div class="area-list">
                        <?php foreach ($current_canvas['areas'] as $area_id => $area): ?>
                            <?php $area_html = get_area_html($area['html_file']); ?>
                            <div class="area-item" data-area-id="<?php echo $area_id; ?>">
                                <div class="area-item-header">
                                    <div class="area-item-name" id="areaName_<?php echo $area_id; ?>">
                                        <?php echo htmlspecialchars($area['name']); ?>
                                    </div>
                                    <div class="area-item-actions">
                                        <button class="btn btn-sm btn-primary edit-area-btn">
                                            <i class="fa-solid fa-edit"></i> 编辑
                                        </button>
                                        <button class="btn btn-sm btn-danger delete-area-btn">
                                            <i class="fa-solid fa-trash"></i> 删除
                                        </button>
                                    </div>
                                </div>
                                <div class="area-item-meta">
                                    分辨率: <?php echo $area['width'] . 'x' . $area['height']; ?> | 位置:
                                    (<?php echo $area['x']; ?>, <?php echo $area['y']; ?>)
                                </div>

                                <!-- 内联编辑表单（默认隐藏） -->
                                <div class="area-edit-form" id="editForm_<?php echo $area_id; ?>"
                                     style="display: none;">
                                    <div class="form-group">
                                        <label class="form-label">区域名称</label>
                                        <input type="text" class="form-input area-edit-name"
                                               value="<?php echo htmlspecialchars($area['name']); ?>">
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label" for="resolution">选择分辨率</label>
                                        <select class="form-select resolution" name="resolution" required>
                                            <option value="">-- 选择预设分辨率 --</option>
                                            <optgroup label="PC常用分辨率">
                                                <?php foreach ($pc_res as $res): ?>
                                                    <option value="<?php echo $res['w'] . 'x' . $res['h']; ?>"><?php echo $res['name']; ?></option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                            <optgroup label="手机常用分辨率">
                                                <?php foreach ($mobile_res as $res): ?>
                                                    <option value="<?php echo $res['w'] . 'x' . $res['h']; ?>"><?php echo $res['name']; ?></option>
                                                <?php endforeach; ?>
                                            </optgroup>
                                        </select>
                                    </div>
                                    <div class="form-group">
                                        <label class="form-label">HTML内容</label>
                                        <textarea
                                                class="form-textarea area-edit-html"><?php echo htmlspecialchars($area_html); ?></textarea>
                                    </div>
                                    <div class="area-edit-actions">
                                        <button class="btn btn-primary btn-sm save-area-edit-btn">保存</button>
                                        <button class="btn btn-secondary btn-sm cancel-area-edit-btn">取消</button>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>

        <!-- 右侧画库区 -->
        <div class="canvas-container" id="canvasContainer">
            <div class="canvas-grid" id="canvasGrid"
                 style="transform: scale(<?php echo $current_canvas['canvas_view']['scale'] / 100; ?>);"></div>
            <div class="canvas-workspace" id="canvasWorkspace"></div>

            <!-- 对齐辅助线 -->
            <div class="alignment-guides" id="alignmentGuides">
                <div class="guide-line horizontal" id="horizontalGuide"></div>
                <div class="guide-line vertical" id="verticalGuide"></div>
            </div>

            <!-- 区域组件（跟随缩放） -->
            <?php if (!empty($current_canvas['areas'])): ?>
                <?php foreach ($current_canvas['areas'] as $area_id => $area): ?>
                    <?php
                    $html_file_path = HTML_FILES_DIR . '/' . $area['html_file'];
                    $html_file_url = str_replace(__DIR__, '', $html_file_path);
                    $html_file_url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . '/html_canvas_data/html_files/' . ltrim($area['html_file'], '/');
                    // 计算缩放后的尺寸
                    $scale = $current_canvas['canvas_view']['scale'] / 100;
                    $scaledWidth = $area['width'] * $scale;
                    $scaledHeight = $area['height'] * $scale;
                    ?>
                    <div
                            class="area-container"
                            data-canvas-id="<?php echo $canvas_id; ?>"
                            data-area-id="<?php echo $area_id; ?>"
                            data-original-width="<?php echo $area['width']; ?>"
                            data-original-height="<?php echo $area['height']; ?>"
                            style="
                                    left: <?php echo $area['x'] * $scale; ?>px;
                                    top: <?php echo $area['y'] * $scale; ?>px;
                                    width: <?php echo $scaledWidth; ?>px;
                                    "
                    >
                        <div class="area-header">
                            <div class="area-title"><?php echo htmlspecialchars($area['name']); ?></div>
                        </div>
                        <iframe src="<?php echo $html_file_url; ?>"
                                style="height: <?php echo $scaledHeight; ?>px;"></iframe>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="empty-hint">
                    <p>画布为空，添加区域后将显示在这里</p>
                </div>
            <?php endif; ?>
        </div>
<?php } ?>
    </div>
</div>

<!-- 核心功能JS -->
<script >
    
    
    /**
 * 节流函数
 * @param {Function} func - 需要节流的函数
 * @param {number} delay - 时间间隔（毫秒）
 * @returns {Function} 节流后的函数
 */
function throttle(func, delay) {
  let lastTime = 0; // 上一次执行的时间戳
  return function(...args) {
    const now = Date.now(); // 当前时间戳
    // 如果当前时间 - 上一次执行时间 >= 间隔时间，则执行函数
    if (now - lastTime >= delay) {
      func.apply(this, args); // 保持this指向和参数传递
      lastTime = now; // 更新上一次执行时间
    }
  };
}

document.addEventListener('DOMContentLoaded', function () {
    <?php if (isset($current_canvas)): ?>
    // 画布核心状态
    const canvasState = {
        scale: <?php echo $current_canvas['canvas_view']['scale']; ?>,
        offsetX: <?php echo $current_canvas['canvas_view']['offsetX']; ?>,
        offsetY: <?php echo $current_canvas['canvas_view']['offsetY']; ?>,
        isDraggingCanvas: false,
        dragStartX: 0,
        dragStartY: 0,
        snapDistance: 10, // 对齐吸附距离
        canvasContainer: document.getElementById('canvasContainer'),
        canvasGrid: document.getElementById('canvasGrid'),
        canvasWorkspace: document.getElementById('canvasWorkspace'),
        alignmentGuides: document.getElementById('alignmentGuides'),
        horizontalGuide: document.getElementById('horizontalGuide'),
        verticalGuide: document.getElementById('verticalGuide'),
        scaleDisplay: document.getElementById('scaleDisplay'),
        canvasId: '<?php echo $canvas_id; ?>',
        project_id: '<?php echo $project_id; ?>',
        sidebar: <?php echo isset($current_canvas['canvas_view']['sidebar'])?$current_canvas['canvas_view']['sidebar']:1; ?>,
    };

    // 初始化画布位置
    canvasState.canvasContainer.scrollLeft =canvasState.offsetX;
    canvasState.canvasContainer.scrollTop = canvasState.offsetY;

    // 左侧菜单
    let toggeSettingBtn = document.getElementById('toggeSetting');
    
    toggeSettingBtn.addEventListener('click', function () {
        //document.querySelector('.sidebar').classList.toggle('hidden');
         $(".tree-sidebar,.sidebar").toggle()
        if(canvasState.sidebar == 0){
            canvasState.sidebar = 1
        }else{
           canvasState.sidebar = 0
        }
        
        saveCanvasViewState();
    })
    
    if(canvasState.sidebar == 0){
      
       $(".tree-sidebar,.sidebar").hide()
    }

    // 1. 画板名称保存
    document.getElementById('saveCanvasNameBtn').addEventListener('click', function () {
        const newName = document.getElementById('canvasNameInput').value.trim();
        if (!newName) {
            alert('画板名称不能为空');
            return;
        }

        fetch(window.location.href, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=rename_canvas&project_id=${canvasState.project_id}&canvas_id=${canvasState.canvasId}&new_name=${encodeURIComponent(newName)}`
        }).then(() => {
            window.location.reload();
        });
    });

    // 2. 画板删除
    document.getElementById('deleteCanvasBtn').addEventListener('click', function () {
        window.location.href = `?action=delete_canvas&project_id=${canvasState.project_id}&canvas_id=${canvasState.canvasId}`;
    });

    // 3. 缩放控制（区域跟随缩放）
    function updateScale(scale) {
        scale = Math.max(10, Math.min(200, scale));
        canvasState.scale = scale;
        const scaleRatio = scale / 100;

        // 更新所有区域的尺寸和位置
        const areaContainers = document.querySelectorAll('.area-container');
        areaContainers.forEach(areaEl => {
            const originalWidth = parseInt(areaEl.dataset.originalWidth);
            const originalHeight = parseInt(areaEl.dataset.originalHeight);

            // 更新尺寸
            areaEl.style.width = `${originalWidth * scaleRatio}px`;
            areaEl.querySelector('iframe').style.height = `${originalHeight * scaleRatio}px`;
        });
    }

    // 缩放按钮事件
    document.getElementById('zoomInBtn').addEventListener('click', () => {
        updateScale(canvasState.scale + 2);
    });
    document.getElementById('zoomOutBtn').addEventListener('click', () => {
        updateScale(canvasState.scale - 2);
    });


    // 5. 区域内联编辑
    document.querySelectorAll('.edit-area-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const areaItem = this.closest('.area-item');
            const areaId = areaItem.dataset.areaId;
            const editForm = document.getElementById(`editForm_${areaId}`);

            // 显示编辑表单
            editForm.style.display = 'block';
        });
    });

    // 取消编辑
    document.querySelectorAll('.cancel-area-edit-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            this.closest('.area-edit-form').style.display = 'none';
        });
    });

    // 保存编辑
    document.querySelectorAll('.save-area-edit-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            const areaItem = this.closest('.area-item');
            const areaId = areaItem.dataset.areaId;
            const editForm = this.closest('.area-edit-form');
            const newName = editForm.querySelector('.area-edit-name').value.trim();
            const newHtml = editForm.querySelector('.area-edit-html').value.trim();
            const resolution = editForm.querySelector('.resolution').value.trim();
            if (!newName) {
                alert('区域名称不能为空');
                return;
            }
            if (!newHtml) {
                alert('HTML内容不能为空');
                return;
            }

            // AJAX提交
            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `action=edit_area_ajax&project_id=${canvasState.project_id}&canvas_id=${canvasState.canvasId}&area_id=${areaId}&area_name=${encodeURIComponent(newName)}&html_content=${encodeURIComponent(newHtml)}&resolution=${resolution}`
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 更新界面
                         window.location.reload();
                        // document.getElementById(`areaName_${areaId}`).textContent = data.name;
                        // editForm.style.display = 'none';

                        // // 刷新区域iframe
                        // const areaContainer = document.querySelector(`.area-container[data-area-id="${areaId}"]`);
                        // const iframe = areaContainer.querySelector('iframe');
                        // iframe.src = iframe.src + '?t=' + new Date().getTime();
                    } else {
                        alert(data.message);
                    }
                });
        });
    });

    // 6. 区域删除
    document.querySelectorAll('.delete-area-btn').forEach(btn => {
        btn.addEventListener('click', function () {
            if (!confirm('确定删除该区域？')) return;

            const areaItem = this.closest('.area-item');
            const areaId = areaItem.dataset.areaId;

            fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `action=delete_area_ajax&project_id=${canvasState.project_id}&canvas_id=${canvasState.canvasId}&area_id=${areaId}`
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === 'success') {
                        areaItem.remove();
                        // 删除画布中的区域
                        document.querySelector(`.area-container[data-area-id="${areaId}"]`).remove();
                    } else {
                        alert(data.message);
                    }
                });
        });
    });

    // 7. 区域拖动（带对齐+缩放适配）
    const areaContainers = document.querySelectorAll('.area-container');
    areaContainers.forEach(areaEl => {
        // 记录拖拽状态和初始值
        let isDragging = false;
        let initialLeft = 0; // 元素初始left（相对于定位父级）
        let initialTop = 0;  // 元素初始top（相对于定位父级）
        let initialX = 0;    // 鼠标初始X（视口坐标）
        let initialY = 0;    // 鼠标初始Y（视口坐标）

        // 开始拖拽（鼠标按下）
        areaEl.addEventListener('mousedown', (e) => {
            isDragging = true;
            areaEl.classList.add('dragging');
            // 记录元素初始定位（相对于定位父级）
            initialLeft = parseInt(areaEl.style.left) || 0;
            initialTop = parseInt(areaEl.style.top) || 0;
            // 记录鼠标初始位置（视口坐标）
            initialX = e.clientX;
            initialY = e.clientY;
        });

        // 实时拖拽（鼠标移动）
        document.addEventListener('mousemove', (e) => {
            if (!isDragging) return;
            // 计算鼠标移动距离
            const dx = e.clientX - initialX;
            const dy = e.clientY - initialY;
            // 计算新位置（初始位置 + 移动距离）
            const newLeft = initialLeft + dx;
            const newTop = initialTop + dy;
            // 更新元素位置
            areaEl.style.left = `${newLeft}px`;
            areaEl.style.top = `${newTop}px`;
        });

        // 结束拖拽（鼠标松开）
        document.addEventListener('mouseup', () => {
            if (isDragging) {
                isDragging = false;
                areaEl.classList.remove('dragging');
                const canvasId = '<?php echo $canvas_id; ?>';
                const areaId = areaEl.dataset.areaId;
                const x = parseInt(areaEl.style.left) || 0;
                const y = parseInt(areaEl.style.top) || 0;
                saveAreaPosition(canvasId, areaId, x, y);
            }
        });

    });

    // 8. 辅助函数
    function saveCanvasViewState() {
        fetch(window.location.href, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=save_canvas_view&project_id=${canvasState.project_id}&canvas_id=${canvasState.canvasId}&scale=${canvasState.scale}&offsetX=${canvasState.offsetX}&offsetY=${canvasState.offsetY}&sidebar=${canvasState.sidebar}`
        }).catch(err => console.error('保存画布状态失败:', err));
    }

    function saveAreaPosition(canvasId, areaId, x, y) {
        fetch(window.location.href, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=save_area_position&project_id=${canvasState.project_id}&canvas_id=${canvasId}&area_id=${areaId}&x=${x}&y=${y}`
        }).catch(err => console.error('保存区域位置失败:', err));
    }

    function showAlignmentGuides(guideX, guideY, areaSize) {
        canvasState.alignmentGuides.style.display = 'block';
        if (guideY !== null) {
            canvasState.horizontalGuide.style.top = `${guideY}px`;
            canvasState.horizontalGuide.style.display = 'block';
        } else {
            canvasState.horizontalGuide.style.display = 'none';
        }
        if (guideX !== null) {
            canvasState.verticalGuide.style.left = `${guideX}px`;
            canvasState.verticalGuide.style.display = 'block';
        } else {
            canvasState.verticalGuide.style.display = 'none';
        }
    }

    function hideAlignmentGuides() {
        canvasState.alignmentGuides.style.display = 'none';
    }

    // 9. 重置视图
    document.getElementById('resetViewBtn').addEventListener('click', function () {
        updateScale(100);
        canvasState.canvasContainer.scrollLeft = 0;
        canvasState.canvasContainer.scrollTop = 0;
        saveCanvasViewState();
    });

    // 10. 新增区域表单提交
    document.getElementById('addAreaForm').addEventListener('submit', function (e) {
        e.preventDefault();
        const formData = new FormData(this);
        fetch(window.location.href, {
            method: 'POST',
            body: new URLSearchParams(formData)
        }).then(() => {
            window.location.reload();
        });
    });
    
    // 对动作进行节流处理（间隔100ms执行一次）
    const throttledScroll = throttle(function(){
         canvasState.offsetX = canvasState.canvasContainer.scrollLeft;
         canvasState.offsetY = canvasState.canvasContainer.scrollTop;
        saveCanvasViewState();
    }, 100);
    // 监听滚动事件，绑定节流后的处理函数
    canvasState.canvasContainer.addEventListener('scroll', throttledScroll);
    
    <?php endif; ?>
});
</script>
<script>
$(function(){
    $("#addCanvasBtn").on("click",function(){
        $("#newCanvasForm").show();
    })
    
    $("#confirmCreateCanvas").on("click",function(){
        let project_id = '<?php echo $project_id; ?>'
        let newName = $("#newCanvasName").val().trim();
        fetch(window.location.href, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `action=create_canvas&project_id=${project_id}&canvas_name=${encodeURIComponent(newName)}`
        }).then(() => {
            window.location.reload();
        });
    })
})

</script>
</body>
</html>